package www.lagou.app;

import org.junit.jupiter.api.Test;
import www.lagou.dao.AccountDao;
import www.lagou.dao.TransactionDao;
import www.lagou.entity.Account;
import www.lagou.entity.Transaction;
import www.lagou.utils.DateUtils;
import www.lagou.utils.DruidUtils;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 作业1：转账操作测试类
 *
 * @author Shuxian Huang
 */
public class TestTransferAccount {

    AccountDao accountDao = new AccountDao();

    TransactionDao transactionDao = new TransactionDao();

    /**
     * 实现cardId向cardId2转账5000
     */
    @Test
    public void transferTest() throws SQLException {
        String cardId = "1122334455";
        String cardId2 = "55443332211";
        //1 查询转出方余额
        Account account = accountDao.findAccountByCard(cardId);
        Account account2 = accountDao.findAccountByCard(cardId2);
        if (account == null || account2 == null) {
            System.out.println("账户卡号错误！");
            return;
        }
        //2 实现转账
        if (account.getBalance() < 5000) {
            System.out.println("余额不足！");
            return;
        }
        Connection con = null;
        try {
            con = DruidUtils.getConnection();
            if (con == null){
                return;
            }
            //开启事务
            con.setAutoCommit(false);
            //账户1余额减5000， 账户2余额加5000
            //记录转账记录
            accountDao.modifyAccountBalance(con, cardId, account.getBalance() - 5000);
            transactionDao.insertTransaction(con, new Transaction(null, cardId, "转出",
                    5000, DateUtils.getDateFormart()));
//            System.out.println(1/0);
            accountDao.modifyAccountBalance(con, cardId2, account2.getBalance() + 5000);
            transactionDao.insertTransaction(con, new Transaction(null, cardId2, "转入",
                    5000, DateUtils.getDateFormart()));
            //提交事务
            con.commit();
            System.out.println("转账成功！");
        }catch (Exception e){
            e.printStackTrace();
            if (con != null) {
                con.rollback();
            }
        }finally {
            if (con != null) {
                con.close();
            }
        }
    }
}
